<?php
namespace App\Services\Admin;

use Illuminate\Support\Facades\DB;

class SceneCntService extends BaseService
{
    /**
     * 场景
     */

    /**
     * 获取场景连列表
     * @param array $pages【start起始页，limit每页记录数】
     * @param int $scene_id
     */
    public function getIndex($pages, $scene_id)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbSceneCnt)
            ->where('del', 1)
            ->where('scene_id', $scene_id);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有了');
        }
        $types = $this->scene_types;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $type_name = array_key_exists($v['type'], $types) ? $types[$v['type']] : '-';
            if ($v['type'] == 1) {
                $cnt = $v['cnt'];
            } else {
                $cnt = file_exists($v['cnt']) ? $v['cnt'] : '';
            }
            $arys[] = [
                'id' => $v['id'],
                'type' => $v['type'],
                'type_name' => $type_name,
                'cnt' => $cnt,
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 添加文件
     * @param int $scid
     * @param string $img 图片
     * @param int $w 宽度
     * @param int $h 高度
     */
    public function addFile($type, $img)
    {
        $fData = [
            'link' => $img,
            'addtime' => toDate(),
        ];
        $lastid = $this->dbConn($this->dbImg)->insertGetId($fData);
        if (!$lastid) {
            return $this->toback(-1, '图库失败');
        }
        return $this->toback();
    }

    /**
     * 场景新增
     * @param array $pas
     */
    public function add($pas)
    {
        $pas['uptime'] = $pas['addtime'] = toDate();
        $res = $this->dbConn($this->dbSceneCnt)->insertGetId($pas);
        if (!$res) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 场景修改
     * @param int $id
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbSceneCnt)->where('id', $id)->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 场景删除
     * @param id $id 场景ID
     * return array
     */
    public function del($id)
    {
        $pas = [
            'del' => 2,
            'deltime' => toDate(),
        ];
        $res = $this->dbConn($this->dbSceneCnt)
            ->where('del', 1)
            ->where('id', $id)
            ->update($pas);
        if (!$res) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}